from flask_restful import Resource, reqparse

from restful.api__.session import login_required_current_user_generate, pid_required_target_post_generate
from restful.model.delete import DeleteInstance
from restful.model.query import QueryOneInstance
from restful.model.tables import Comment, Blog
from restful.model.update import UpdateInstance
from restful.response import ResponseNotFound, ResponseSuccess, ResponseConflict


class CommentOrCancel(Resource):
    @login_required_current_user_generate
    @pid_required_target_post_generate
    def post(self, target_post, current_user):
        parser = reqparse.RequestParser()
        parser.add_argument('content', required=True, help="评论不能为空")
        data= parser.parse_args()


        post = QueryOneInstance(Blog, {'id': target_post.id})

        if not post:
            return ResponseNotFound("帖子不存在或已删除")

        UpdateInstance(Comment(uid=current_user.id,pid=target_post.id), data)
        return ResponseSuccess(msg="评论成功")

    @login_required_current_user_generate
    def delete(self,cid,current_user):
        comment = QueryOneInstance(Comment,{'id':cid,'uid':current_user.id})

        if not comment:
            return ResponseConflict("评论不存在")

        DeleteInstance(comment)
        return ResponseSuccess("已成功删除评论")


